﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Telerik.Web.UI;
using SMA.GENTEv1;

public partial class Protegidos_Administracao_Cadastros__wf_wfFolhaPagamento : System.Web.UI.Page
{
    int idContrato = 0;
    int idProcessoContrato = 0;
    private const int idTipoDocumento = 15;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["idProcessoContrato"] != null)
            idProcessoContrato = Int32.Parse(Request.QueryString["idProcessoContrato"].ToString());

        if (Request.QueryString["idContrato"] != null)
            idContrato = Int32.Parse(Request.QueryString["idContrato"].ToString());

        if (!IsPostBack)
        {
            AcertaCampos();
            CarregaDataFim();
        }
    }
    #region Eventos

    #region Eventos - Geral
    protected void btnSalvar_Click(object sender, EventArgs e)
    {

    }
    protected void btnIncluir_Click(object sender, EventArgs e)
    {
        Novo();
    }
    protected void btnLimpar_Click(object sender, EventArgs e)
    {
        LimparCampos();
    }
    #endregion

    #region Eventos - ComboBox
    protected void rcbFormaPagamento_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        //if (int.Parse(rcbFormaPagamento.SelectedValue) == 1)
        //{
        //    dvPagUnico.Visible = true;
        //    dvPag2.Visible = false;
        //}
        //else
        //{
        //    dvPagUnico.Visible = false;
        //    dvPag2.Visible = true;
        //}
    }
    protected void rcbTpDia1_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        if (rcbTpDia1.SelectedValue == "Corrido")
        {
            CarregaDia(rcbDia1);
            rcbDia1.Enabled = true;
        }
        else
        {
            CarregaDiaUtil(rcbDia1);
            rcbDia1.Enabled = true;
        }
    }
    protected void rcbTpDia2_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        if (rcbTpDia2.SelectedValue == "Corrido")
        {
            CarregaDia(rcbDia2);
            rcbDia2.Enabled = true;
        }
        else
        {
            CarregaDiaUtil(rcbDia2);
            rcbDia2.Enabled = true;
        }
    }
    protected void rcbTpDia3_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        if (rcbTpDia3.SelectedValue == "Corrido")
        {
            CarregaDia(rcbDia3);
            rcbDia3.Enabled = true;
        }
        else
        {
            CarregaDiaUtil(rcbDia3);
            rcbDia3.Enabled = true;
        }
    }
    protected void rcb13P1_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        if (int.Parse(rcb13P1.SelectedValue) == 1)
            dv13Parc1.Visible = false;
        else
            dv13Parc1.Visible = true;
    }
    protected void rcb13P2_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        if (int.Parse(rcb13P2.SelectedValue) == 1)
            dv13Parc2.Visible = false;
        else
            dv13Parc2.Visible = true;
    }
    protected void rcb13P1Forma_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        if (rcb13P1Forma.SelectedValue == "Corrido")
        {
            CarregaDia(rcb13P1Dia);
            rcb13P1Dia.Enabled = true;
        }
        else
        {
            CarregaDiaUtil(rcb13P1Dia);
            rcb13P1Dia.Enabled = true;
        }
    }
    protected void rcb13P2Forma_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        if (rcb13P2Forma.SelectedValue == "Corrido")
        {
            CarregaDia(rcb13P2Dia);
            rcb13P2Dia.Enabled = true;
        }
        else
        {
            CarregaDiaUtil(rcb13P2Dia);
            rcb13P2Dia.Enabled = true;
        }
    }
    #endregion

    #region Eventos - Grid
    protected void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
    {
        Pesquisa();
    }
    protected void RadGrid1_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        if (e.CommandName == "Visualizar")
        {
            //string acao = ((System.Web.UI.WebControls.LinkButton)(e.CommandSource)).Text;
            int idWfConfig = Int32.Parse(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["IdWfConfig"].ToString());

            CarregarDados(idWfConfig);
        }
        if (e.CommandName == "Desativar")
        {
            int idWfConfig = Int32.Parse(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["IdWfConfig"].ToString());

            WorkflowConfig wfConfig = new WorkflowConfig(idWfConfig);
            wfConfig.Status = new StatusConfiguracaoWorkflow(3);
            wfConfig.Salvar();

            AtualizarGrid();
        }

        //    string link = string.Empty;
        //    int idProcessoContrato = Int32.Parse(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["IdProcessoContrato"].ToString());

        //    ProcessoContrato processo = new ProcessoContrato(idProcessoContrato);

        //    link = "_wf/wf" + processo.TipoProcesso.Url + "?id=" + idProcessoContrato.ToString();

        //    //Server.Transfer("_wf/wfFolhaPagamento.aspx?id=" + idProcessoContrato.ToString());
        //    Server.Transfer(link);

    }
    #endregion
    
    #endregion

    #region Metodos

    #region Metodos - Geral
    private void CarregarDados(int idWfConfig)
    {
        LimparCampos();

        WorkflowConfig wfConfig = new WorkflowConfig(idWfConfig);

        txtDtInicio.SelectedDate = wfConfig.DataInicio;
        txtDtFim.Text = Convert.ToDateTime(wfConfig.DataFim).ToString("dd/MM/yyyy");

        WorkflowConfigData wfConfigData = new WorkflowConfigData();
        List<WorkflowConfigData> listWf = wfConfigData.SelectPor(idWfConfig);


        rcb13P1.SelectedValue = "1";
        rcb13P2.SelectedValue = "1";

        foreach (WorkflowConfigData item in listWf)
        {
            switch (item.TipoPagamento.IdTipoPagamento)
            {
                case 1: //1	Pagamento Principal
                    rcbFormaPagamento.SelectedValue = "2";
                    dvPag2.Visible = true;

                    rcbTpDia3.SelectedValue = item.TipoDia;

                    if (item.TipoDia == "Corrido")
                        CarregaDia(rcbDia3);
                    else
                        CarregaDiaUtil(rcbDia3);

                    rcbDia3.SelectedValue = item.Dia.ToString();
                    rcbDia3.Enabled = true;
                    break;
                case 2: //2	Pagamento Adiantamento
                    rcbFormaPagamento.SelectedValue = "2";
                    dvPag2.Visible = true;

                    rcbTpDia2.SelectedValue = item.TipoDia;

                    if (item.TipoDia == "Corrido")
                        CarregaDia(rcbDia2);
                    else
                        CarregaDiaUtil(rcbDia2);

                    rcbDia2.SelectedValue = item.Dia.ToString();
                    rcbDia2.Enabled = true;
                    break;
                case 3: //3	Pagamento Unico
                    rcbFormaPagamento.SelectedValue = "1";
                    dvPagUnico.Visible = true;

                    rcbTpDia1.SelectedValue = item.TipoDia;

                    if (item.TipoDia == "Corrido")
                        CarregaDia(rcbDia1);
                    else
                        CarregaDiaUtil(rcbDia1);

                    rcbDia1.SelectedValue = item.Dia.ToString();
                    rcbDia1.Enabled = true;
                    break;
                case 4: //4	13° - Pagamento 1° Parcela
                    rcb13P1.SelectedValue = "2";
                    dv13Parc1.Visible = true;

                    rcb13P1Forma.SelectedValue = item.TipoDia;

                    if (item.TipoDia == "Corrido")
                        CarregaDia(rcb13P1Dia);
                    else
                        CarregaDiaUtil(rcb13P1Dia);

                    rcb13P1Dia.SelectedValue = item.Dia.ToString();
                    rcb13P1Dia.Enabled = true;
                    break;
                case 5: //5	13° - Pagamento 2ª Parcela
                    rcb13P2.SelectedValue = "2";
                    dv13Parc2.Visible = true;

                    rcb13P2Forma.SelectedValue = item.TipoDia;

                    if (item.TipoDia == "Corrido")
                        CarregaDia(rcb13P2Dia);
                    else
                        CarregaDiaUtil(rcb13P2Dia);

                    rcb13P2Dia.SelectedValue = item.Dia.ToString();
                    rcb13P2Dia.Enabled = true;
                    break;
                default:
                    break;
            }
        }
    }
    private void Novo()
    {
        try
        {
            Contrato contrato = new Contrato(idContrato);

            if (txtDtInicio.SelectedDate >= contrato.DataImplantacao)
            {
                DateTime dtFimContrato;

                if (contrato.DataProrrogacao == DateTime.MinValue)
                    dtFimContrato = contrato.DataFimVigencia;
                else
                    dtFimContrato = contrato.DataProrrogacao;

                if (txtDtInicio.SelectedDate < dtFimContrato)
                {
                    bool grava = true;

                    WorkflowConfig wfConfigPesq = new WorkflowConfig();
                    List<WorkflowConfig> listWfConfig = wfConfigPesq.SelectPor(idTipoDocumento, idContrato, idProcessoContrato);

                    int idStatus = 1;

                    foreach (WorkflowConfig item in listWfConfig)
                    {
                        if (item.Status.IdStatusConfiguracaoWorkflow == 4)
                        {
                            lblResultado.Text = "Já existe um parâmetros  futuro cadastrado!";
                            grava = false;
                        }
                        else
                        {
                            if (item.Status.IdStatusConfiguracaoWorkflow == 1)
                            {
                                if (txtDtInicio.SelectedDate > item.DataInicio)
                                {
                                    idStatus = 4;

                                    WorkflowConfig wfConfigAtualiza = new WorkflowConfig();
                                    wfConfigAtualiza.IdWfConfig = item.IdWfConfig;

                                    wfConfigAtualiza.TipoDocumento = item.TipoDocumento;
                                    wfConfigAtualiza.DataInicio = item.DataInicio;
                                    wfConfigAtualiza.DataFim = txtDtInicio.SelectedDate - new TimeSpan(1, 0, 0, 0, 0);
                                    wfConfigAtualiza.Status = item.Status;
                                    wfConfigAtualiza.IdContrato = item.IdContrato;
                                    wfConfigAtualiza.IdProcessoContrato = item.IdProcessoContrato;

                                    wfConfigAtualiza.Salvar();
                                }
                                else
                                {
                                    lblResultado.Text = "Data início menor que a data de início (" + Convert.ToDateTime(item.DataInicio).ToString("dd/MM/yyyy") + ") ativa!";
                                    grava = false;
                                }
                            }
                        }
                    }

                    if (grava)
                    {
                        WorkflowConfig wfConfig = new WorkflowConfig();
                        wfConfig.TipoDocumento = new TipoDocumento(idTipoDocumento);
                        wfConfig.DataInicio = txtDtInicio.SelectedDate;

                        if (contrato.DataProrrogacao == DateTime.MinValue)
                            wfConfig.DataFim = contrato.DataFimVigencia;
                        else
                            wfConfig.DataFim = contrato.DataProrrogacao;

                        wfConfig.Status = new StatusConfiguracaoWorkflow(idStatus);
                        wfConfig.IdContrato = idContrato;
                        wfConfig.IdProcessoContrato = idProcessoContrato;

                        wfConfig.Salvar();

                        GravarParametros(wfConfig);

                        AtualizarGrid();
                        lblResultado.Text = "Parâmetros cadastrados com sucesso!";
                    }

                }
                else
                {
                    lblResultado.Text = "Data de início maior que a data final!";
                }

            }
            else
            {
                lblResultado.Text = "Data de início menor o que a data de implantação (" + contrato.DataImplantacao.ToString("dd/MM/yyyy") + ")!";
            }
        }
        catch (Exception ex)
        {
            lblResultado.Text = "Erro:" + ex.Message;
        }

    }
    private void GravarParametros(WorkflowConfig wfConfig)
    {
        List<WorkflowConfigData> listWfConfigData = new List<WorkflowConfigData>();

        if (rcbFormaPagamento.SelectedValue == "1")
        {
            //Pagamento Unico
            WorkflowConfigData wfConfigData = new WorkflowConfigData();
            wfConfigData.WfConfig = wfConfig;
            wfConfigData.TipoDia = rcbTpDia1.SelectedValue;
            wfConfigData.Dia = int.Parse(rcbDia1.SelectedValue);
            wfConfigData.TipoPagamento = new TipoPagamento(3);
            wfConfigData.Salvar();
        }
        else if (rcbFormaPagamento.SelectedValue == "2")
        {
            //Adiantamento
            WorkflowConfigData wfConfigData1 = new WorkflowConfigData();
            wfConfigData1.WfConfig = wfConfig;
            wfConfigData1.TipoDia = rcbTpDia2.SelectedValue;
            wfConfigData1.Dia = int.Parse(rcbDia2.SelectedValue);
            wfConfigData1.TipoPagamento = new TipoPagamento(1);
            wfConfigData1.Salvar();

            //Principal
            WorkflowConfigData wfConfigData2 = new WorkflowConfigData();
            wfConfigData2.WfConfig = wfConfig;
            wfConfigData2.TipoDia = rcbTpDia3.SelectedValue;
            wfConfigData2.Dia = int.Parse(rcbDia3.SelectedValue);
            wfConfigData2.TipoPagamento = new TipoPagamento(2);
            wfConfigData2.Salvar();
        }

        if (rcb13P1.SelectedValue == "2")
        {
            //13° - Pagamento 1° Parcela
            WorkflowConfigData wfConfigData = new WorkflowConfigData();
            wfConfigData.WfConfig = wfConfig;
            wfConfigData.TipoDia = rcb13P1Forma.SelectedValue;
            wfConfigData.Dia = int.Parse(rcb13P1Dia.SelectedValue);
            wfConfigData.TipoPagamento = new TipoPagamento(4);
            wfConfigData.Salvar();
        }

        if (rcb13P2.SelectedValue == "2")
        {
            //13° - Pagamento 2° Parcela
            WorkflowConfigData wfConfigData = new WorkflowConfigData();
            wfConfigData.WfConfig = wfConfig;
            wfConfigData.TipoDia = rcb13P2Forma.SelectedValue;
            wfConfigData.Dia = int.Parse(rcb13P2Dia.SelectedValue);
            wfConfigData.TipoPagamento = new TipoPagamento(5);
            wfConfigData.Salvar();
        }

    }
    private void AtualizarGrid()
    {
        Pesquisa();
        RadGrid1.DataBind();
    }
    private void AcertaCampos()
    {
        btnSalvar.Visible = false;
        dvPagUnico.Visible = false;
        dvPag2.Visible = false;
        dv13Parc1.Visible = false;
        dv13Parc2.Visible = false;

        rcbDia1.Enabled = false;
        rcbDia2.Enabled = false;
        rcbDia3.Enabled = false;

        rcb13P1Dia.Enabled = false;
        rcb13P2Dia.Enabled = false;
    }
    private void LimparCampos()
    {
        AcertaCampos();
    }
    private void CarregaDataFim()
    {
        ProcessoContrato processo = new ProcessoContrato(idProcessoContrato);
        Contrato contrato = new Contrato(processo.IdContrato);

        if (contrato.DataProrrogacao == DateTime.MinValue)
            txtDtFim.Text = contrato.DataFimVigencia.ToString("dd/MM/yyyy");
        else
            txtDtFim.Text = contrato.DataProrrogacao.ToString("dd/MM/yyyy");

    }
    #endregion

    #region Metodos - ComboBox
    protected void CarregaDia(RadComboBox combo)
    {
        combo.Items.Clear();
        combo.Text = "";
        for (int i = 31; i >= 1; i--)
        {
            combo.Items.Insert(0, new RadComboBoxItem(i.ToString(), i.ToString()));
        }
    }
    protected void CarregaDiaUtil(RadComboBox combo)
    {
        combo.Items.Clear();
        combo.Text = "";
        for (int i = 27; i >= 1; i--)
        {
            combo.Items.Insert(0, new RadComboBoxItem(i.ToString() + "º", i.ToString()));
        }
    }
    #endregion

    #region Metodos - Grid
    private void Pesquisa()
    {
        RadGrid1.DataSource = CarregaParametros();
    }
    protected List<WorkflowConfig> CarregaParametros()
    {
        WorkflowConfig wfConfig = new WorkflowConfig();
        List<WorkflowConfig> listWfConfig = wfConfig.SelectPor(idTipoDocumento, idContrato, idProcessoContrato);

        return listWfConfig;
    }
    #endregion
    
    #endregion
    
}
